<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\library\Auth;
use app\common\model\BankCard;
use app\common\model\PolicyRelation;
use fast\Random;
use think\Db;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'mobile,nickname';
    protected $selectpageFields = 'id,mobile,nickname,username';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $query = $this->model->with('group');

//            if(!$this->auth->isSuperAdmin()){
//                $query->where(['user.ptype' => 1,"user.pid"=> $this->auth->getCompany()->id]);
//            }
            if (!$this->auth->isSuperAdmin()) {
                if ($this->auth->getCompany()->pid == 0) {
                    $query->where(["user.company_id" => $this->auth->getCompany()->id]);
                } else {
                    $userIds = [];
                    $directUser = Tools::getCompanyChildUser($this->auth->getCompany()->id);//查询下级机构的直属代理
                    if(count($directUser) > 0){
                        foreach ($directUser as $key => $val){
                            $userIds[] = $val->id;
                            $childUser = Tools::getUserChild($val->id,4);//查询直属代理的所有下级代理
                            $userIds = array_merge($userIds,$childUser);
                        }
                    }

                    $query->where(["user.id" => ["in", $userIds]]);
                }
            }

            $list = $query->where(["is_virtual" => 1])->where($where)->order($sort, $order)->paginate($limit);

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $company = Lib::getCompany($v->company_id);
                $v->company_name = $company ? $company->name : "暂无";
                $parentInfo = Tools::getParentInfo(2,$v->id);
                $v->parent = [
                    "type" => $parentInfo['type'],
                    "name" => $parentInfo['type'] == 1 ? "后台" : $parentInfo['obj']->nickname,
                ];
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    public function bank($ids = ""){
        $bank = BankCard::where(["sale_id" => $ids])->find();

        $this->view->assign('bank', $bank);
        return $this->view->fetch();
    }

    public function qr($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("id",$ids);
        $this->view->assign("company_id",$row->company_id);
        return $this->view->fetch();
    }

    public function policy($ids){
        $user= $this->model->get($ids);
        if (false === $this->request->isPost()) {
            $product = Lib::getUserProduct(2, $ids,"all");

            if (count($product) > 0) {
                foreach ($product as $key => &$val) {
                    $val["policy"] = Lib::getUserPolicy(2, $ids, $val['id']);
                }
                unset($val);
            }

            if($user->ptype == 1 && $user->pid == $this->auth->getCompany()->id){
                $operate = true;
            }else{
                $operate = false;
            }

            $this->view->assign("product",$product);
            $this->view->assign("operate",$operate);
            $this->assignconfig("user",$ids);
            return $this->view->fetch();
        }

        $relationId = $this->request->post("relation_id");
        $productId = $this->request->post("product_id");

        $stock = Lib::getStocks(2,$ids,$productId);
        if($stock && $stock->stocks != 0){
            $this->error("代理库存未清，不允许调整政策！");
        }

        $childs = Tools::getUserChild($ids,3);
        if(count($childs) > 0){
            foreach ($childs as $key => $val){
                $childStock = Lib::getStocks(2,$val['id'],$productId);
                if($childStock && $childStock->stocks != 0){
                    $this->error("下级代理【{$val['name']}】库存未清，不允许调整政策！");
                }
            }
        }

        $result = false;
        Db::startTrans();
        try {
            PolicyRelation::where(["main_type" => 2,"main_id" => $ids,"product_id" => $productId])->update(["default" => 0]);

            $relation = PolicyRelation::get($relationId);
            $relation->default = 1;
            $relation->default_time = time();
            $result = $relation->save();

            if($user->is_setting == 0){
                $user->is_setting = 1;
                $user->save();
            }

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success("操作成功！");
    }

    public function cut($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost() === false) {
            $this->view->assign("pid",$row->id);
            return $this->view->fetch();
        }
        $param = $this->request->post("row/a");

        if ($param['mobile'] && \app\common\model\User::getByMobile($param['mobile'])) {
            $this->error("手机号已存在！");
            return false;
        }

        $child = \app\admin\model\User::get($param['child']);

        $ip = request()->ip();
        $time = time();
        $password = "fd123456";

        $data = [
            'username' => $param['mobile'],
            'password' => $password,
            'email'    => "",
            'mobile'   => $param['mobile'],
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
        ];

        $params = array_merge($data, [
            'company_id'  => $row->company_id,
            'pid'  => $row->id,
            'ptype'  => 2,
            'unreal'  => 1,//是否为真实用户
            'nickname'  => $param['name'],
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $params['password'] = md5(md5($password) . $params['salt']);
        $user = \app\common\model\User::create($params, true);
        if($user){
            $child->pid = $user->id;
            $child->ptype = 2;
            $child->save();

            $this->success("添加成功！");
        }else{
            $this->error("添加失败！");
        }
    }

}
